<template>
  <div class="contentView" v-loading="formLoading" :style="`height:${contentHeight}px`">
    <div class="routeHeader mb-5px">
      <el-button
        v-if="!formType.includes('lookup')"
        @click="submitForm('save')"
        type="primary"
        v-hasPermi="['config:craft-task-bill:save']"
        :disabled="formLoading"
        >保 存</el-button
      >
      <el-button
        v-if="!formType.includes('lookup')"
        @click="submitForm('submitTo')"
        type="primary"
        v-hasPermi="['config:craft-task-bill:submit']"
        :disabled="formLoading"
        >提 交</el-button
      >
      <el-button @click="goBack">关 闭</el-button>
    </div>
    <el-scrollbar :style="`height:${contentHeight - 63}px`">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :inline="true"
        label-width="110px"
        v-loading="formLoading"
      >
        <el-form-item label="产品编号" prop="productNumber">
          <el-input
            disabled
            v-model="formData.productNumber"
            placeholder="请输入产品编号"
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            disabled
            v-model="formData.productName"
            placeholder="请输入产品名称"
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item label="产品图号" prop="productDrawingNumber ">
          <el-input
            disabled
            v-model="formData.productDrawingNumber"
            placeholder="请输入产品图号"
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item label="产品规格" prop="productStandard">
          <el-input
            disabled
            v-model="formData.productStandard"
            placeholder="请输入产品规格"
            class="!w-220px"
          />
        </el-form-item>

        <el-form-item label="部件编码" prop="partNumber">
          <el-input
            disabled
            v-model="formData.partNumber"
            placeholder="请输入部件编码"
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item label="部件名称" prop="partName">
          <el-input
            disabled
            v-model="formData.partName"
            placeholder="请输入部件名称"
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item label="图纸图号" prop="partDrawingNumber">
          <el-input
            disabled
            v-model="formData.partDrawingNumber"
            placeholder="请输入图纸图号"
            class="!w-220px"
          />
        </el-form-item>
        <el-form-item label="部件规格" prop="partSpecification">
          <el-input
            disabled
            v-model="formData.partSpecification"
            placeholder="请输入部件规格"
            class="!w-220px"
          />
        </el-form-item>
        <el-divider />
        <div class="currentProcess">
          <div>
            <span class="text-16px font-600">当前工艺: </span>
            <span>{{ formData.currentVersion }}</span>
          </div>
          <div class="ml-16px">
            <!-- <el-button type="primary" @click="setUpProcess">历史工艺路线</el-button> -->
            <el-button v-if="!formType.includes('lookup')" type="primary" @click="addLine"
              >新增行</el-button
            >
            <el-button v-if="!formType.includes('lookup')" @click="copyProcess">复制</el-button>
          </div>
        </div>
      </el-form>
      <!-- 表单数据 -->
      <div class="pb-20px">
        <el-table
          ref="multipleTableRef"
          default-expand-all
          row-key="parentIndex"
          v-loading="formLoading"
          :data="craftData"
          border
        >
          <el-table-column label="工序号" type="index" align="center" width="80">
            <template #default="scope">
              {{ formatIndex(scope.row, scope.row.index) }}
            </template>
          </el-table-column>
          <el-table-column label="工序名称" align="center">
            <template #default="scope">
              <div v-if="scope.row.children">
                <el-select
                  :disabled="formType.includes('lookup')"
                  @change="selectProcess(scope.row)"
                  v-model="scope.row.dictProcessName"
                  placeholder="请选择工序名称"
                  class="!w-220px"
                >
                  <el-option
                    v-for="(dict, index) in getIntDictOptions(DICT_TYPE.CRAFT_PROCESS_NAME)"
                    :key="index"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </div>
              <div v-else>{{ scope.row.subProcessName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="关系类型" align="center">
            <template #default="scope">
              <div v-if="scope.row.children != null">
                <el-select
                  disabled
                  v-model="scope.row.dictRelationType"
                  placeholder="请选择工序名称"
                  class="!w-220px"
                >
                  <el-option
                    v-for="(dict, index) in getIntDictOptions('dict_relation_type')"
                    :key="index"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="作业指导书" align="center">
            <template #default="scope">
              <div v-if="scope.row.children != null">
                <el-tag
                  class="tag"
                  :type="'success'"
                  disable-transitions
                  @click="jobGuideBook(scope.row, scope.row.parentIndex)"
                  >{{ scope.row.instructorBook }}</el-tag
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="!formType.includes('lookup')"
            label="操作"
            header-align="center"
            align="right"
            width="160"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                v-if="scope.$index !== 0 && scope.row.children != null"
                link
                type="primary"
                @click="paramsUp(scope.row.parentIndex)"
                >上移</el-button
              >
              <el-button
                v-if="scope.row.parentIndex !== craftData.length - 1 && scope.row.children != null"
                link
                type="primary"
                @click="paramsDown(scope.row.parentIndex)"
                >下移</el-button
              >
              <el-button
                v-if="scope.row.children !== null"
                link
                type="danger"
                @click="removeLine(scope.row.parentIndex, scope.row.id)"
                >移除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-scrollbar>
    <!-- 表单弹窗：指导书 -->
    <CraftTaskBook ref="bookFormRef" @success="openBook" />
    <!-- 表单弹窗：工艺复制 -->
    <CraftTaskCopy ref="copyRef" @success="openCopy" />
  </div>
</template>
<script setup lang="ts">
import * as CraftTaskBillApi from '@/api/config/craftTaskBill'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import CraftTaskBook from './CraftTaskBook.vue'
import CraftTaskCopy from './CraftTaskCopy.vue'
import { useTagsViewStore } from '@/store/modules/tagsView'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const craftData = ref<any[]>([]) // 表单数据
// const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const { query } = useRoute() // 路由的查询
const formData = ref({
  productNumber: undefined,
  productName: undefined,
  productDrawingNumber: undefined,
  productStandard: undefined,
  partNumber: undefined,
  partName: undefined,
  partSpecification: undefined,
  partDrawingNumber: undefined,
  currentVersion: undefined
})
const formRules = reactive({
  productNumber: [{ required: true, message: '产品编号不能为空', trigger: 'change' }],
  productName: [{ required: true, message: '产品名称不能为空', trigger: 'change' }],
  partNumber: [{ required: true, message: '部件编码不能为空', trigger: 'change' }],
  partName: [{ required: true, message: '部件名称不能为空', trigger: 'change' }],
  partDrawingNumber: [{ required: true, message: '图纸图号不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async () => {
  const id = query.id as any
  const type = query.type as any
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CraftTaskBillApi.getCraftTaskBill(id)
      const data = await CraftTaskBillApi.getCraftTaskBillList(id)
      if (data) {
        craftData.value = data.map((item, index) => {
          item.parentIndex = index
          let childIndex = index
          if (item.children) {
            item.children.map((child, index) => {
              child.childrenIndex = childIndex
              child.index = index
              child.parentIndex = index
              return child
            })
          }
          return item
        })
      }
    } finally {
      formLoading.value = false
    }
  }
}

// 刷新数据
const multipleTableRef = ref()
const selectProcess = async (row) => {
  console.log(999)
  const dict = row.dictProcessName
  const data = await CraftTaskBillApi.getSublist(dict)
  row.dictRelationType = data.dictRelationType
  row.children = data.children
  if (multipleTableRef.value) {
    multipleTableRef.value.doLayout()
  }
  craftData.value.map((item, index) => {
    item.parentIndex = index
    let childIndex = index
    if (item.children) {
      item.children.map((child, index) => {
        child.childrenIndex = childIndex
        child.parentIndex = index
        child.index = index
        return child
      })
    }
    return item
  })
}

/** 提交表单 */
const submitForm = async (val) => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const id = Number(query.id)
    const data = formData.value
    craftData.value.forEach((item) => {
      item.children = []
      item.sort = item.parentIndex + 1
    })
    if (val === 'save') {
      const taskData = {
        ...data,
        taskId: id,
        dictIsSubmit: 0,
        list: craftData.value
      }

      await CraftTaskBillApi.updateCraftTaskBill(taskData)
      message.success(t('common.updateSuccess'))
      goBack()
    } else {
      const taskData = {
        ...data,
        taskId: id,
        dictIsSubmit: 1,
        list: craftData.value
      }
      await CraftTaskBillApi.updateCraftTaskBill(taskData)
      message.success(t('common.updateSuccess'))
      goBack()
    }
  } finally {
    formLoading.value = false
  }
}

// 指导书查看
const bookFormRef = ref()
const unmBook = ref()
const jobGuideBook = (row, index) => {
  unmBook.value = index
  if (!row.dictProcessName) {
    return message.notifyError('请选择工序')
  }
  const typeData = formType.value
  const dict = {
    dictProcessName: row.dictProcessName,
    partName: formData.value.partName,
    productNumber: formData.value.productNumber
  }
  const id = row.id
  bookFormRef.value.open(dict, typeData, id)
}

//指导书数量
const openBook = (num) => {
  craftData.value[unmBook.value].instructorBook = num
}

// 复制工艺
const copyRef = ref()
const copyProcess = () => {
  copyRef.value.open(listId.value)
}

// 复制工艺的数据
const list = ref([])
const listId = ref<number[]>([])
const openCopy = (val, id: number) => {
  listId.value = [id]
  list.value = val.map((item) => {
    item.id = ''
    if (item.children) {
      item.children.map((child) => {
        child.parentId = ''
        return child
      })
    }
    return item
  })
  craftData.value = list.value
  craftData.value.map((item, index) => {
    item.parentIndex = index
    let childIndex = index
    if (item.children) {
      item.children.map((child, index) => {
        child.childrenIndex = childIndex
        child.index = index
        child.parentIndex = index
        return child
      })
    }
    return item
  })
}

// 新增行
const addLine = () => {
  const data = {
    children: [],
    dictProcessName: '',
    dictRelationType: '',
    instructorBook: ''
  }
  craftData.value.push(data)
  craftData.value.map((item, index) => {
    item.parentIndex = index
    let childIndex = index
    if (item.children) {
      item.children.map((child, index) => {
        child.childrenIndex = childIndex
        child.index = index
        child.parentIndex = index
        return child
      })
    }
    return item
  })
}

// 上移
const paramsUp = (index) => {
  if (index > 0) {
    const temp = craftData.value[index]
    craftData.value.splice(index, 1)
    craftData.value.splice(index - 1, 0, temp)
    craftData.value.map((item, index) => {
      item.parentIndex = index
      let childIndex = index
      if (item.children) {
        item.children.map((child, index) => {
          child.childrenIndex = childIndex
          child.index = index
          child.parentIndex = index
          return child
        })
      }
      return item
    })
  }
}

// 下移
const paramsDown = (index) => {
  if (index < craftData.value.length - 1) {
    const temp = craftData.value[index]
    craftData.value.splice(index, 1)
    craftData.value.splice(index + 1, 0, temp)
    craftData.value.map((item, index) => {
      item.parentIndex = index
      let childIndex = index
      if (item.children) {
        item.children.map((child, index) => {
          child.childrenIndex = childIndex
          child.index = index
          child.parentIndex = index
          return child
        })
      }
      return item
    })
  }
}

/** 序号 */
const formatIndex = (row, index) => {
  if (row.children) {
    return `${row.parentIndex + 1}`
  } else {
    // row.sort = row.childrenIndex + 1 + '-' + (index + 1)
    return `${row.childrenIndex + 1}-${index + 1}`
  }
}

// 删除
const removeLine = async (index, id?: number) => {
  craftData.value.splice(index, 1)
  craftData.value.map((item, index) => {
    item.parentIndex = index
    return item
  })
  if (id) {
    await CraftTaskBillApi.deleteCraftTaskConf(id)
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    productNumber: undefined,
    productName: undefined,
    partNumber: undefined,
    productDrawingNumber: undefined,
    productStandard: undefined,
    partName: undefined,
    partSpecification: undefined,
    partDrawingNumber: undefined,
    currentVersion: undefined
  }
  formRef.value?.resetFields()
}

// 返回
const tagsViewStore = useTagsViewStore()
const route = useRouter() // 路由
const goBack = () => {
  //获取当前路由并删除tagView
  tagsViewStore.delView(route.currentRoute.value)
  route.push({
    path: '/config/config/craftCuttingWeight/craftTaskBill'
  })
}

const contentHeight = ref(0)
const refreshData = async () => {
  contentHeight.value = document.body.clientHeight - 127
}

onMounted(async () => {
  refreshData()
  await open()
})
</script>
<style lang="scss" scoped>
.currentProcess {
  display: flex;
  margin-bottom: 10px;
  // justify-content: center;
  // align-items: center;
}
.el-divider--horizontal {
  margin: 10px 0;
  border-top: 1px solid #ebeef5;
}
</style>
<style lang="scss" scoped>
.tag {
  cursor: pointer;
}
.indexChildren {
  display: flex;
  justify-content: flex-end;
  // text-align: right;
}
::v-deep.el-table .cell {
  display: flex;
  justify-content: center;
  align-items: center;
}
.contentView {
  padding: 10px;
  background: #fff;
}
.tableView {
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
    cursor: default;
    .el-input__inner {
      cursor: default !important;
      text-align: center;
    }
  }
}
</style>
